package com.zrf.gulimall.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrf.gulimall.commnon.core.exception.CustomException;
import com.zrf.gulimall.common.database.utils.PageUtils;
import com.zrf.gulimall.common.database.utils.Query;
import com.zrf.gulimall.member.dao.MemberDao;
import com.zrf.gulimall.member.entity.MemberEntity;
import com.zrf.gulimall.member.service.MemberService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

	@Override
	public MemberEntity getMember(String loginacct, String password) {
    	if (Objects.isNull(loginacct)) {
    		throw new CustomException("用户名不能为空");
		}
		if (Objects.isNull(password)) {
			throw new CustomException("密码不能为空");
		}
		MemberEntity memberEntity = this.lambdaQuery()
				.eq(MemberEntity::getUsername, loginacct)
				.or()
				.eq(MemberEntity::getMobile, loginacct)
				.one();
		if (Objects.isNull(memberEntity)) {
			throw new CustomException("用户名或密码不正确");
		}
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		boolean matches = passwordEncoder.matches(password, memberEntity.getPassword());
		if (!matches) {
			throw new CustomException("用户名或密码不正确");
		}
		return memberEntity;
	}

}